<?php
$app->group('/gallery',function() use($app){
    $app->get('/',function() use($app){
        $baseUrl=$app->request()->getScriptName();
        $app->render('jandan/index.php', array('baseUrl' => $baseUrl), 'body');
        $app->render('layout.php', array('baseUrl' => $baseUrl, 'title' => 'Jandan Images', 'scripts' => array('/js/gallery.js'), 'nav' => 'jandan'));
    })->name('gallery-home');
    $app->group('/api',function() use($app){
        $app->get('/tasks',function() use($app){
            $pageNumber = intval($app->request->get('pageNumber'));
            $pageNumber = max($pageNumber, 1);
            $pageSize=10;
            $db = $app->db;
            $total = intval($db->scalar('select count(1) as total from five_colors'));
            $model = array('gallery' => array());
            if ($total > 0) {
                $totalPages = ceil($total / $pageSize * 1.0);
                $pageNumber = min($totalPages, $pageNumber);
                $pages = array();
                if ($pageNumber > 1) {
                    $pages[] = array('title' => 'Prev', 'pageNumber' => $pageNumber - 1);
                } else {
                    $pages[] = array('title' => 'Prev', 'pageNumber' => 0);
                }
                $pages[] = array('title' => $pageNumber, 'pageNumber' => $pageNumber);
                if ($pageNumber < $totalPages) {
                    $pages[] = array('title' => 'Next', 'pageNumber' => $pageNumber + 1);
                } else {
                    $pages[] = array('title' => 'Next', 'pageNumber' => -1);
                }
                $model['gallery'] = $db->query(sprintf('select url from five_colors order by id desc limit %d,%d', ($pageNumber - 1) * $pageSize, $pageSize), null, PDO::FETCH_NUM);
                $model['pagination'] = array('totalPages' => $totalPages, 'pageNumber' => $pageNumber, 'pages' => $pages);
            }
            $app->json($model);
        })->name('gallery-api-images');
    });
});